using System;
using System.ServiceModel;
using System.Windows.Input;

// ReSharper disable UnusedMember.Global

namespace MvcMusicStore.BI.Client.Commands
{
  public abstract class ServiceCommandBase<TInterface, TClient> : CommandCore, ICommand
    where TInterface : class
    where TClient : ClientBase<TInterface>
  {
    private TClient mClient;

    private bool IsClientCreated
    {
      get { return mClient != null; }
    }

    #region ICommand Members

    public Boolean CanExecute(Object parameter)
    {
      return CanExecute(GetClient()) && !IsExecuting;
    }

    public void Execute(Object parameter)
    {
      try
      {
        if (!CanExecute(GetClient())) return;

        if (OnExecutingCore())
        {
          Execute(GetClient());
        }
      }
      catch (Exception exception)
      {
        OnExecutedCore(CommandExecutionResult.FromException(exception));
      }
    }

    #endregion

    private TClient GetClient()
    {
      if (IsClientCreated) return mClient;
      mClient = CreateServiceClient();
      return mClient;
    }

    private static TClient CreateServiceClient()
    {
      var wClient = (TClient) Activator.CreateInstance(typeof (TClient),
                                                       "BasicHttpBinding_ISales");
      return wClient;
    }

    private static EndpointAddress GetEndpointAddress()
    {
      return new EndpointAddress("http://localhost:56580/Sales.svc");
    }

    private static WSHttpBinding CreateWsHttpBinding()
    {
      var binding = new WSHttpBinding();
      // Default values:
      //binding.CloseTimeout = TimeSpan.FromMinutes(1);
      //binding.SendTimeout = TimeSpan.FromMinutes(1);
      //binding.OpenTimeout = TimeSpan.FromMinutes(1);
      //binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
      //binding.BypassProxyOnLocal = false;
      //binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
      //binding.MaxBufferPoolSize = 524288;
      //binding.MaxReceivedMessageSize = 65536;
      //binding.MessageEncoding = WSMessageEncoding.Text;
      //binding.TextEncoding = System.Text.Encoding.UTF8;
      //binding.UseDefaultWebProxy = true;
      //binding.AllowCookies = false;
      return binding;
    }

    protected abstract bool CanExecute(TClient client);

    protected abstract void Execute(TClient client);
  }
}

// ReSharper restore UnusedMember.Global